<?php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Auth\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Auth\Form\LoginForm;
use Auth\Form\LoginFilter;

class IndexController extends AbstractActionController {

	public function indexAction() {
		return new ViewModel();
	}

	public function loginAction() {
		$form = new LoginForm();
		$form->get('submit')->setValue('Login');
		$messages = null;

		$request = $this->getRequest();
		if ($request->isPost()) {
			$config = (Object) $this->getServiceLocator()->get('Config');
			$form->setInputFilter(new LoginFilter($this->getServiceLocator()));
			$form->setData($request->getPost());
			if ($form->isValid()) {
				$data = (Object) $form->getData();
				$password = $this->getStaticSalt() . $data->password; // static_salt . $data['usr_password'] . $password
				$authService = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
				$adapter = $authService->getAdapter();
				$adapter->setIdentityValue($data->username); //$data['usr_name']
				$adapter->setCredentialValue($password);
				$authResult = $authService->authenticate();
				if ($authResult->isValid()) {
					echo 'Login successed!';
					$identity = $authResult->getIdentity();
					var_dump($identity);die;
					$authService->getStorage()->write($identity);
					if ($data->rememberme) {
						$sessionManager = new \Zend\Session\SessionManager();
						$sessionManager->rememberMe($config->session_time);
					}
					//- return $this->redirect()->toRoute('home');
				}else{
					$messages = 'Username or password is not valid!'; //$authResult->messages;
				}
			}
		}

		return new ViewModel(array(
			'form' => $form,
			'messages' => $messages,
		));
	}

	public function getStaticSalt() {
		$staticSalt = '';
		$config = $this->getServiceLocator()->get('Config');
		$staticSalt = $config['static_salt'];
		return $staticSalt;
	}

}
